﻿using DTcms.Common;
using DTcms.Model;
using DTcms.Web.Mvc.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Web.Mvc;

namespace DTcms.Web.Mvc.Areas.Admin.Controllers
{
    public class ChannelController : ManageController
    {
        protected BaseApi _service = new BaseApi();
        protected int totalCount = 0;
        protected Model.manager managerModel = new Model.manager();
        protected string _action;
        protected int _id;
        protected int _site_id;
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            managerModel = GetAdminInfo();
            _action = DTRequest.GetQueryString("action");
            _id = DTRequest.GetQueryInt("id");
            _site_id = DTRequest.GetQueryInt("site_id");
            ViewBag.action = _action;
            ViewBag.id = _id;
        }

        #region 页面创建
        [ChkAdminScript("sys_channel_field", DTEnums.ActionEnum.View)]
        public ActionResult Attribute_Field_List()
        {
            return View();
        }

        [ChkAdminScript("sys_channel_field", DTEnums.ActionEnum.View)]
        public ActionResult Attribute_Field_Edit()
        {
            Model.article_attribute_field model = new Model.article_attribute_field();
            if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
            {
                if (_id == 0)
                {
                    return ResultMsg("传输参数不正确！", "back");
                }
                model = _service.AttributeInfo(_id);
                if (model == null)
                {
                    return ResultMsg("记录不存在或已被删除！", "back");
                }
                string script = "$('#name').removeAttr('ajaxurl').removeAttr('datatype').attr('disabled','disabled');";
                if (model.is_sys == 1)
                {
                    script += "$('#control_type').attr('disabled','disabled');";
                }
                script += "os.render();";
                ViewBag.ClientScript = Jscript(script);
            }
            return View(model);
        }

        [ChkAdminScript("sys_channel_manage", DTEnums.ActionEnum.View)]
        public ActionResult Channel_Edit()
        {
            Model.site_channel model = new Model.site_channel();
            List<Model.url_rewrite> url_list = new List<Model.url_rewrite>();
            if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
            {
                if (_id == 0)
                {
                    return ResultMsg("传输参数不正确！", "back");
                }
                model = _service.ChannelInfo(_id);
                if (model == null)
                {
                    return ResultMsg("记录不存在或已被删除！", "back");
                }
                //绑定URL配置列表
                url_list = new BLL.url_rewrite().GetList(model.name);
                ViewBag.ClientScript = Jscript("$('#name').attr('ajaxurl', '/admin_ajax/channel_name_validate?old_channel_name=" + Utils.UrlEncode(model.name) + "').focus();");
            }
            else
            {
                ViewBag.ClientScript = Jscript("$('#name').attr('ajaxurl', '/admin_ajax/channel_name_validate');");
            }
            if (model.channel_thums == null)
            {
                //默认最大只允许设置3种尺寸(暂时只开启一种做为系统默认)
                model.channel_thums = new List<Model.site_channel_thum>();
                model.channel_thums.Add(new Model.site_channel_thum()
                {
                    id = 0,
                    class_id = 1,
                    title = "封面尺寸",
                    width = siteConfig.thumbnailwidth,
                    height = siteConfig.thumbnailheight,
                    typeid = 0,
                    is_lock = 1
                });
                //缩略图
                model.channel_thums.Add(new Model.site_channel_thum()
                {
                    id = 0,
                    class_id = 2,
                    title = "缩略图尺寸",
                    width = siteConfig.thumbnailwidth,
                    height = siteConfig.thumbnailheight,
                    typeid = 0,
                    is_lock = 1
                });
            }
            ViewBag.urlList = url_list;
            ViewBag.fieldList = _service.AttributeBind("", "is_sys desc,sort_id asc,id desc");
            return View(model);
        }

        [ChkAdminScript("sys_channel_manage", DTEnums.ActionEnum.View)]
        public ActionResult Channel_List()
        {
            return View();
        }

        [ChkAdminScript("sys_site_manage", DTEnums.ActionEnum.View)]
        public ActionResult Site_Edit()
        {
            Model.sites model = new Model.sites();
            if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
            {
                if (_id == 0)
                {
                    return ResultMsg("传输参数不正确！", "back");
                }
                model = _service.SiteInfo(_id);
                if (model == null)
                {
                    return ResultMsg("记录不存在或已被删除！", "back");
                }
                ViewBag.ClientScript = Jscript("$('#build_path').attr('ajaxurl', '/admin_ajax/site_path_validate?old_build_path=" + Utils.UrlEncode(model.build_path) + "').focus();");
            }
            else
            {
                ViewBag.ClientScript = Jscript("$('#build_path').attr('ajaxurl', '/admin_ajax/site_path_validate');");
            }
            List<SelectListItem> siteList = new List<SelectListItem>();
            siteList.Add(new SelectListItem() { Text = "独立运行...", Value = "0" });
            siteList.AddRange(_service.SiteTreeBind("is_lock=0 and id<>" + _id, "is_default desc,sort_id asc,id desc"));
            ViewBag.siteList = siteList;
            return View(model);
        }

        [ChkAdminScript("sys_site_manage", DTEnums.ActionEnum.View)]
        public ActionResult Site_List()
        {
            return View();
        }

        [ChkAdminScript("sys_article_tags", DTEnums.ActionEnum.View)]
        public ActionResult Tags_Edit()
        {
            Model.article_tags model = new Model.article_tags();
            if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
            {
                if (_id == 0)
                {
                    return ResultMsg("传输参数不正确！", "back");
                }
                model = _service.TagsInfo(_id);
                if (model == null)
                {
                    return ResultMsg("记录不存在或已被删除！", "back");
                }
                ViewBag.ClientScript = Jscript("$('#call_index').attr('ajaxurl', '/admin_ajax/tags_validate?old_name=" + Utils.UrlEncode(model.call_index) + "');");
            }
            else
            {
                ViewBag.ClientScript = Jscript("$('#call_index').attr('ajaxurl', '/admin_ajax/tags_validate');");
            }
            return View(model);
        }

        [ChkAdminScript("sys_article_tags", DTEnums.ActionEnum.View)]
        public ActionResult Tags_List()
        {
            return View();
        }
        #endregion

        #region 页面数据绑定
        #region 组合SQL查询语句
        protected string TagsCombSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and title like  '%" + _keywords + "%'");
            }
            return strTemp.ToString();
        }
        #endregion
        #region 数据绑定
        [ChkAdminJson("sys_article_tags", DTEnums.ActionEnum.View)]
        public JsonResult TagsList(string keywords, int page = 1, int limit = 10)
        {
            string strWhere = "id > 0" + TagsCombSqlTxt(keywords);
            string strOrder = "sort_id asc,id desc";
            DataTable resultList = _service.TagsBind(strWhere, strOrder, out totalCount, page, limit);
            return Json(new { status = 1, msg = "", item = resultList, totalCount = totalCount });
        }
        #endregion

        #region 组合SQL查询语句==========================
        protected string SiteCombSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and (title like  '%" + _keywords + "%' or name like  '%" + _keywords + "%' or build_path like '%" + _keywords + "%' or domain like '%" + _keywords + "%')");
            }
            return strTemp.ToString();
        }
        #endregion
        #region 数据绑定
        [ChkAdminJson("sys_site_manage", DTEnums.ActionEnum.View)]
        public JsonResult SiteList(string keywords, int page = 1, int limit = 10)
        {
            string strWhere = "id > 0" + SiteCombSqlTxt(keywords);
            string strOrder = "sort_id asc,id desc";
            var resultList = _service.SiteBind(strWhere, strOrder, page, limit);
            DataTable Items = DataHelper.ListToDataTable(resultList.Items);
            DataTable oldData = Items.Clone();
            if (resultList.TotalItems > 0)
            {
                oldData.Columns.Add("inherit", Type.GetType("System.String"));
                foreach (DataRow item in Items.Rows)
                {
                    DataRow row = oldData.NewRow();
                    row["build_path"] = item["build_path"];
                    row["title"] = item["title"];
                    row["inherit_id"] = item["inherit_id"];
                    row["inherit"] = new BLL.sites().GetTitle(Utils.ObjToInt(item["inherit_id"]));
                    row["domain"] = item["domain"];
                    row["site_type"] = item["site_type"];
                    row["sort_id"] = item["sort_id"];
                    row["is_default"] = item["is_default"];
                    row["id"] = item["id"];
                    oldData.Rows.Add(row);
                }
            }
            return Json(new { status = 1, msg = "", item = oldData, totalCount = resultList.TotalItems });
        }
        #endregion

        #region 组合SQL查询语句
        protected string ChannelCombSqlTxt(int _site_id, string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (_site_id > 0)
            {
                strTemp.Append(" and site_id=" + _site_id);
            }
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and (name like  '%" + _keywords + "%' or title like '%" + _keywords + "%')");
            }
            return strTemp.ToString();
        }
        #endregion
        #region 数据绑定
        [ChkAdminJson("sys_channel_manage", DTEnums.ActionEnum.View)]
        public JsonResult ChannelList(string keywords, int site_id = 0, int page = 1, int limit = 10)
        {
            string strWhere = "id > 0" + ChannelCombSqlTxt(site_id, keywords);
            string strOrder = "sort_id asc,id desc";
            var resultList = _service.ChannelBind(strWhere, strOrder, page, limit);
            DataTable Items = DataHelper.ListToDataTable(resultList.Items);
            DataTable oldData = Items.Clone();
            if (resultList.TotalItems > 0)
            {
                oldData.Columns.Add("siteTitle", Type.GetType("System.String"));
                foreach (DataRow item in Items.Rows)
                {
                    DataRow row = oldData.NewRow();
                    row["name"] = item["name"];
                    row["title"] = item["title"];
                    row["is_albums"] = item["is_albums"];
                    row["is_attach"] = item["is_attach"];
                    row["is_spec"] = item["is_spec"];
                    row["is_type"] = item["is_type"];
                    row["sort_id"] = item["sort_id"];
                    row["id"] = item["id"];
                    row["siteTitle"] = new BLL.sites().GetTitle(Utils.ObjToInt(item["site_id"]));
                    oldData.Rows.Add(row);
                }
            }
            return Json(new { status = 1, msg = "", item = oldData, totalCount = resultList.TotalItems });
        }
        #endregion

        #region 组合SQL查询语句==========================
        protected string FiledCombSqlTxt(string _control_type, string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(_control_type))
            {
                strTemp.Append(" and control_type='" + _control_type + "'");
            }
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and (name like  '%" + _keywords + "%' or title like '%" + _keywords + "%')");
            }
            return strTemp.ToString();
        }
        #endregion
        #region 数据绑定
        [ChkAdminJson("sys_channel_field", DTEnums.ActionEnum.View)]
        public JsonResult FiledList(string keywords, string control_type, int page = 1, int limit = 10)
        {
            string strWhere = "id > 0" + FiledCombSqlTxt(control_type, keywords);
            string strOrder = "is_sys desc,sort_id asc,id desc";
            var resultList = _service.AttributeBind(strWhere, strOrder, page, limit);
            return Json(new { status = 1, msg = "", item = resultList.Items, totalCount = resultList.TotalItems });
        }
        #endregion
        #endregion

        #region 页面的其他操作
        #region 删除
        [HttpPost]
        [ChkAdminJson("sys_article_tags", DTEnums.ActionEnum.Delete)]
        public JsonResult TagsDelete(List<int> ids)
        {
            return _service.TagsDelete(ids);
        }

        [HttpPost]
        [ChkAdminJson("sys_site_manage", DTEnums.ActionEnum.Delete)]
        public JsonResult SiteDelete(List<int> ids)
        {
            return _service.SiteDelete(ids);
        }

        [HttpPost]
        [ChkAdminJson("sys_channel_manage", DTEnums.ActionEnum.Delete)]
        public JsonResult ChannelDelete(List<int> ids)
        {
            return _service.ChannelDelete(ids);
        }

        [HttpPost]
        [ChkAdminJson("sys_channel_field", DTEnums.ActionEnum.Delete)]
        public JsonResult AttributeDelete(List<int> ids)
        {
            return _service.AttributeDelete(ids);
        }
        #endregion
        #region 个别字段修改
        //设置推荐
        [HttpPost]
        [ChkAdminJson("sys_article_tags", DTEnums.ActionEnum.Edit)]
        public JsonResult TagsRed(int id, bool is_lock)
        {
            BLL.article_tags bll = new BLL.article_tags();
            if (bll.UpdateFile("id=" + id, "is_red=" + (is_lock ? 1 : 0)))
            {
                return Json(new { status = 1, msg = "设置推荐成功！" });
            }
            return Json(new { status = 0, msg = "设置推荐失败！" });
        }

        [HttpPost]
        [ChkAdminJson("sys_site_manage", DTEnums.ActionEnum.Edit)]
        public JsonResult SiteDefault(int id, bool is_default)
        {
            BLL.sites bll = new BLL.sites();
            if (bll.UpdateFile("", "is_default=0"))
            {
                if (bll.UpdateFile("id=" + id, "is_default=" + (is_default ? 1 : 0)))
                {
                    BLL.sites siteBll = new BLL.sites();
                    siteBll.SetCache(siteBll.GetModel(id));
                    return Json(new { status = 1, msg = "设置默认成功！" });
                }
            }
            return Json(new { status = 0, msg = "设置默认失败！" });
        }

        [HttpPost]
        [ChkAdminJson("sys_article_tags", DTEnums.ActionEnum.Edit)]
        public JsonResult TagsReds(List<int> ids)
        {
            return _service.TagsRed(ids);
        }

        [HttpPost]
        [ChkAdminJson("sys_article_tags", DTEnums.ActionEnum.Edit)]
        public JsonResult TagsFiledSave(string field, int value, int id = 0)
        {
            if (string.IsNullOrEmpty(field) || id == 0)
            {
                return Json(new { status = 0, msg = "参数错误！" });
            }
            BLL.article_tags bll = new BLL.article_tags();
            if (bll.UpdateFile("id=" + id, field + "=" + value))
            {
                return Json(new { status = 1, msg = "修改成功！" });
            }
            return Json(new { status = 0, msg = "修改失败！" });
        }

        [HttpPost]
        [ChkAdminJson("sys_site_manage", DTEnums.ActionEnum.Edit)]
        public JsonResult SiteFiledSave(string field, int value, int id = 0)
        {
            if (string.IsNullOrEmpty(field) || id == 0)
            {
                return Json(new { status = 0, msg = "参数错误！" });
            }
            BLL.sites bll = new BLL.sites();
            if (bll.UpdateFile("id=" + id, field + "=" + value))
            {
                return Json(new { status = 1, msg = "修改成功！" });
            }
            return Json(new { status = 0, msg = "修改失败！" });
        }

        [HttpPost]
        [ChkAdminJson("sys_channel_manage", DTEnums.ActionEnum.Edit)]
        public JsonResult ChannelFiledSave(string field, int value, int id = 0)
        {
            if (string.IsNullOrEmpty(field) || id == 0)
            {
                return Json(new { status = 0, msg = "参数错误！" });
            }
            BLL.site_channel bll = new BLL.site_channel();
            if (bll.UpdateFile("id=" + id, field + "=" + value))
            {
                return Json(new { status = 1, msg = "修改成功！" });
            }
            return Json(new { status = 0, msg = "修改失败！" });
        }

        [HttpPost]
        [ChkAdminJson("sys_channel_field", DTEnums.ActionEnum.Edit)]
        public JsonResult AttributeFiledSave(string field, int value, int id = 0)
        {
            if (string.IsNullOrEmpty(field) || id == 0)
            {
                return Json(new { status = 0, msg = "参数错误！" });
            }
            BLL.article_attribute_field bll = new BLL.article_attribute_field();
            if (bll.UpdateFile("id=" + id, field + "=" + value))
            {
                return Json(new { status = 1, msg = "修改成功！" });
            }
            return Json(new { status = 0, msg = "修改失败！" });
        }
        #endregion

        #region 保存
        [HttpPost, ValidateInput(false),CustomValidateAntiForgeryToken]
        public ActionResult TagsSave(Model.article_tags t)
        {
            SaveModel save = _service.TagsSave(_action, _id, t);
            save.url = save.status == 0 ? "back" : "../channel/tags_list";
            return Json(save);
        }

        [HttpPost, ValidateInput(false), CustomValidateAntiForgeryToken]
        public ActionResult SiteSave(Model.sites t)
        {
            SaveModel save = _service.SiteSave(_action, _id, t);
            save.url = save.status == 0 ? "back" : "../channel/site_list";
            return Json(save);
        }

        [HttpPost, ValidateInput(false), CustomValidateAntiForgeryToken]
        public ActionResult ChannelSave(Model.site_channel t)
        {
            SaveModel save = _service.ChannelSave(_action, _id, t);
            save.url = save.status == 0 ? "back" : "../channel/channel_list";
            return Json(save);
        }

        [HttpPost, ValidateInput(false), CustomValidateAntiForgeryToken]
        public ActionResult AttributeSave(Model.article_attribute_field t)
        {
            SaveModel save = _service.AttributeSave(_action, _id, t);
            save.url = save.status == 0 ? "back" : "../channel/attribute_field_list";
            return Json(save);
        }
        #endregion
        #endregion
    }
}
